import axios from "axios";

const servie = axios.create({
    responseType:"arraybuffer"
});

servie.interceptors.request.use(config=>{
    config.headers['Authorization'] = window.sessionStorage.getItem("tokenStr");
    return  config;
},error => {
    console.error(error)
})

servie.interceptors.response.use(resp=>{
    const headrs = resp.headers;
    let reg =  RegExp(/application\/json/);
    if(headrs["content-type"].match(reg)){
        resp.data = unitToString(resp.data);
    }else {
        let fileDowLoad = require("js-file-download");
        let fileName = headrs["content-disposition"].split(";")[1].split("filename=")[1];
        let contentType = headrs["content-type"];
        fileName = decodeURIComponent(fileName);//中文名格式转换，防止乱码
        fileDowLoad(resp.data,fileName,contentType);//文件下载
    }
},error => {
    console.error(error);
})

function unitToString(unitArray){
    let encodeString = String.fromCharCode.apply(null,new Uint8Array(unitArray));
    let decodeString = decodeURIComponent(escape(encodeString));
    return JSON.parse(decodeString);
}


let base = "";
export const downLoadRequest = (url,params)=>{
    return servie({
        method:"get",
        url:`${base}${url}`,
        data:params,
    })
}

export default servie;